﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;

namespace Firefly.Framework.Components
{
    public abstract class DrawableComponent : UpdateableComponent, IDrawableComponent
    {
        public DrawableComponent()
            : this(null)
        {
        }

        public DrawableComponent(Game game)
            : base(game)
        {
            Visible = true;
            DrawOrder = 0;
        }

        #region IDrawable Members

        public event EventHandler DrawOrderChanged;
        public event EventHandler VisibleChanged;

        private int _drawOrder;
        private bool _visible;
        
        [ContentSerializer(Optional = true)]
        public int DrawOrder
        {
            get { return _drawOrder; }
            set
            {
                if (value != _drawOrder)
                {
                    _drawOrder = value;
                    NotifyDrawOrderChanged();
                }
            }
        }
        [ContentSerializer(Optional = true)]
        public bool Visible
        {
            get { return _visible; }
            set
            {
                if (value != _visible)
                {
                    _visible = value;
                    NotifyVisibleChanged();
                }
            }
        }

        protected void NotifyDrawOrderChanged()
        {
            EventHandler handler = DrawOrderChanged;

            if (handler != null)
            {
                handler(this, new EventArgs());
            }
        }

        protected void NotifyVisibleChanged()
        {
            EventHandler handler = VisibleChanged;

            if (handler != null)
            {
                handler(this, new EventArgs());
            }
        }

        public virtual void Draw(GameTime gameTime)
        {
            if (Visible)
            {
                Children.Draw(gameTime);
            }
        }

        #endregion

        #region IHasContent Members

        public virtual void LoadContent()
        {
            Children.LoadContent();
        }

        public virtual void UnloadContent()
        {
            if (!Disposed)
            {
                Children.UnloadContent();
            }
        }

        #endregion

        #region IDisposable Members

        protected override void Dispose(bool disposing)
        {
            if (!Disposed)
            {
                if (disposing)
                {
                    UnloadContent();
                }

                Disposed = true;
            }
        }

        #endregion
    }
}